package com.btkjgc.utils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.supercsv.io.CsvBeanReader;
import org.supercsv.io.ICsvBeanReader;
import org.supercsv.prefs.CsvPreference;
 

public class CsvUploadFileUtil
{

	public static MultipartFile getMultipartFile(String fileName,
			MultipartHttpServletRequest request)
	{
		MultipartFile mfile = request.getFile(fileName);
		return mfile;
	}
 
	public static ICsvBeanReader getCsvBeanReader(MultipartFile uploadedFile,
			String newHeader)
	{
		try
		{
			InputStream stream = uploadedFile.getInputStream();
			if (newHeader != null)
			{
				String s = IOUtils.toString(stream);
				String[] oldHeader = s.split("\\r", 2);
				String str = s.replaceFirst(oldHeader[0], newHeader);
				stream = new ByteArrayInputStream(str.getBytes(Charset
						.forName("UTF-8")));
			}
			return new CsvBeanReader(new InputStreamReader(stream, "UTF-8"),// "utf-8"
					CsvPreference.EXCEL_PREFERENCE);
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		return null;
	}

}
